#!/usr/bin/perl
use strict;
use FindBin;
use File::Basename;
use Getopt::Long;

use ServerAdapter;
use AutoCfg;
use DeployUtils;
use DeployLock;
use BuildUtils;

sub usage {
    my $pname = $FindBin::Script;

    print("Usage: $pname [-v|--verbose 0|1] [--envpath EnvPath] [--version VERSION]");
    print("\n");
    print("       --envpath:          example:SYS-A/MODULE-X/SIT\n");
    print("       --version:          version number\n");

    exit(1);
}

sub main {
    my ( $isHelp, $isVerbose, $envPath, $version, $buildNo );

    GetOptions(
        'h|help'      => \$isHelp,
        'v|verbose=i' => \$isVerbose,
        'envpath=s'   => \$envPath,
        'version=s'   => \$version
    );

    usage() if ( defined($isHelp) );

    my $deployUtils = DeployUtils->new();
    my $deployEnv   = $deployUtils->deployInit( $envPath, $version );

    $envPath = $deployEnv->{NAME_PATH};
    $version = $deployEnv->{VERSION};

    my $optionError = 0;
    if ( not defined($envPath) or $envPath eq '' ) {
        $optionError = 1;
        print("ERROR: EnvPath not defined by option --envpath or Environment:NAME_PATH\n");
    }
    if ( not defined($version) or $version eq '' ) {
        $optionError = 1;
        print("ERROR: Version not defined by option --version or Environment:VERSION\n");
    }

    if ( $optionError == 1 ) {
        usage();
    }

    my $namePath = $deployEnv->{NAME_PATH};
    my $envName  = $deployEnv->{ENV_NAME};

    my $lock      = DeployLock->new($deployEnv);
    my $appLockId = $lock->lockEnvApp($DeployLock::WRITE);
    my $sqlLockId = $lock->lockEnvSql($DeployLock::WRITE);

    END {
        local $?;
        if ( defined($lock) ) {
            $lock->unlockEnvApp($appLockId);
            $lock->unlockEnvSql($sqlLockId);
        }
    }

    my $serverAdapter = ServerAdapter->new();
    my $verInfo       = $serverAdapter->getEnvVer( $deployEnv, $version );
    my $buildNo       = $verInfo->{buildNo};
    my $buildEnv      = $deployUtils->deployInit( $envPath, $version, $buildNo );

    $serverAdapter->releaseVerToEnv( $buildEnv, 'releasing' );

    my $hasError   = 0;
    my $buildUtils = BuildUtils->new();
    $hasError = $buildUtils->release2Env($buildEnv);

    if ( $hasError != 0 ) {
        print("ERROR: Release $namePath version:$version build($buildNo) to $envName failed.\n");
        $serverAdapter->releaseVerToEnv( $buildEnv, 'release-failed' );
    }
    else {
        print("FINE: Release $namePath version:$version build($buildNo) to $envName success.\n");
        $serverAdapter->releaseVerToEnv( $buildEnv, 'released' );
    }

    return $hasError;
}

exit main();
